package com.gcxy.conf.exception.handler;

import com.gcxy.conf.exception.annotation.GlobalException;
import com.gcxy.conf.exception.exception.IGlobalException;
import com.gcxy.conf.result.R;
import com.gcxy.conf.result.ResultCodeEnum;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 违反约束异常
 * ConstraintViolationException：通常发生在违反数据完整性约束发生的异常，即数据格式错误
 *
 * @author shineTan
 * @date 2022/12/23 17:26
 */
@GlobalException(throwable = ConstraintViolationException.class)
public class ConstraintViolationExceptionHandler implements IGlobalException<R, ConstraintViolationException> {

    @Override
    public R exception(ConstraintViolationException throwable, HttpServletRequest request, HttpServletResponse response) {
        return BaseThrowExceptionHandler.exception(throwable, ResultCodeEnum.REQUEST_PARAM_ERROR,
                () -> throwable.getConstraintViolations().stream().map(ConstraintViolation::getMessageTemplate).collect(Collectors.joining(",")));
    }
}
